package com.pmt.feedplayer.translate

import platform.AVFoundation.*
import platform.Foundation.*

actual class PlayerManager private constructor() {
    
    private var player: AVPlayer? = null
    private var playerItem: AVPlayerItem? = null
    private var audioSampleRate: Double = 44100.0
    
    actual fun loadVideo(videoUri: String) {
        // 停止当前播放
        release()
        
        // 创建视频URL
        val videoURL = NSURL(string = videoUri) ?: NSURL.fileURLWithPath(videoUri)
        
        // 创建AVPlayerItem
        playerItem = AVPlayerItem(URL = videoURL)
        
        // 设置音频输出配置
        configureAudioOutput()
        
        // 创建并配置AVPlayer
        player = AVPlayer(playerItem = playerItem)
        
        // 添加观察者来监控播放状态
        addPlayerObservers()
    }
    
    private fun configureAudioOutput() {
        // 配置音频会话
        val audioSession = AVAudioSession.sharedInstance()
        val errorPtr = memScoped {
            alloc<ObjCObjectVar<NSError?>>()
        }
        
        audioSession.setCategory(
            category = AVAudioSessionCategoryPlayback,
            mode = AVAudioSessionModeDefault,
            options = 0u,
            error = errorPtr.ptr
        )
        
        audioSession.setActive(true, options = 0u, error = errorPtr.ptr)
    }
    
    private fun addPlayerObservers() {
        // 监听播放状态变化
        playerItem?.addObserver(
            forKeyPath = "status",
            options = NSKeyValueObservingOptionNew,
            context = null
        ) { keyPath, object, change, context ->
            if (keyPath == "status" && object is AVPlayerItem) {
                when (object.status) {
                    AVPlayerItemStatusReadyToPlay -> {
                        println("视频准备就绪")
                        // 自动开始播放
                        play()
                    }
                    AVPlayerItemStatusFailed -> {
                        println("视频加载失败: ${object.error?.localizedDescription}")
                    }
                    AVPlayerItemStatusUnknown -> {
                        println("视频状态未知")
                    }
                }
            }
        }
        
        // 监听播放结束
        playerItem?.addObserver(
            forKeyPath = "playbackBufferEmpty",
            options = NSKeyValueObservingOptionNew,
            context = null
        ) { keyPath, object, change, context ->
            if (keyPath == "playbackBufferEmpty" && object is AVPlayerItem) {
                if (object.playbackBufferEmpty) {
                    println("缓冲区为空，等待加载")
                }
            }
        }
    }
    
    actual fun play() {
        player?.play()
    }
    
    actual fun pause() {
        player?.pause()
    }
    
    actual fun seekTo(position: Long) {
        val seekTime = CMTimeMake(value = position.toLong(), timescale = 1000)
        player?.seekToTime(seekTime)
    }
    
    actual fun getCurrentPosition(): Long {
        val currentTime = player?.currentTime() ?: CMTimeMake(0, 1)
        return (CMTimeGetSeconds(currentTime) * 1000).toLong()
    }
    
    actual fun getDuration(): Long {
        val duration = playerItem?.duration ?: CMTimeMake(0, 1)
        return if (CMTIME_IS_INDEFINITE(duration)) {
            0
        } else {
            (CMTimeGetSeconds(duration) * 1000).toLong()
        }
    }
    
    actual fun isPlaying(): Boolean {
        return player?.rate ?: 0.0 > 0.0
    }
    
    // 获取AVPlayer实例用于UIKitView
    fun getAVPlayer(): AVPlayer? {
        return player
    }
    
    actual fun release() {
        // 移除观察者
        playerItem?.removeObserverForKeyPath("status")
        playerItem?.removeObserverForKeyPath("playbackBufferEmpty")
        
        // 停止播放
        player?.pause()
        
        // 释放资源
        playerItem = null
        player = null
    }
    
    actual companion object {
        private var instance: PlayerManager? = null
        
        actual fun getInstance(): PlayerManager {
            if (instance == null) {
                instance = PlayerManager()
            }
            return instance!!
        }
    }
}